package com.junit;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hcfly.utils.ESClient;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.junit.Test;

import java.io.IOException;

public class HighLightQueryDemo {

    private static final ObjectMapper mapper = new ObjectMapper();
    private static final String index = "fruit";
    private static final String type = "species";
    private static final RestHighLevelClient client = ESClient.getClient();


    @Test
    public void highLightQuery() throws IOException {
        /**
         * highlight查询，会将查询的关键字进行高亮显示
         * 
         */
        SearchRequest request = new SearchRequest(index);
        request.types(type);
        // 1,指定查询条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchQuery("disc", "可爱香甜诱人"));
        // 2，指定高亮显示的字段和前缀
        HighlightBuilder highlightBuilder  = new HighlightBuilder();
        highlightBuilder.field("disc", 10)
                .preTags("<font color='red'>")
                .postTags("</font>");
        builder.highlighter(highlightBuilder);
        request.source(builder);


        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
        for (SearchHit hit : resp.getHits().getHits()) {
            System.out.println(hit.getHighlightFields().get("disc"));
        }



    }

}
